layui.use(['form','layer','upload'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery;
    var upload = layui.upload,pid = null;
    $.post("/user/centerDate",function(res){
        pid = res.data.pId;
        $("#id").val(res.data.id);
        $("#name").val(res.data.name);
        $("#userName").val(res.data.userName);
        $("#roleName").val(res.data.roleInfo.roleName);
        $("#state").val(res.data.state);
        $("#stateStr").val(res.data.state===1?"正常使用":"限制使用");
        var ImgObj=new Image();
        ImgObj.src= res.data.url;
        ImgObj.onload=function(){
            if(ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0))
            {
                $("#updateImg").attr("src",res.data.url);
                return true;
            } else {
                $("#updateImg").attr("src",'/static/images/face.jpg');
                return false;
            }
        }
        ImgObj.onerror=function(){
            console.log('error');
            $("#updateImg").attr("src",'/static/images/face.jpg');
        }

    });

    form.on("submit(editUser)",function(data){
        //弹出loading
        var index = top.layer.msg('数据保存中，请稍候...',{icon: 16,time:false,shade:0.8});
        $.post("/user/userEdit",data.field,function(res){
            if (res.data){
                layer.close(index);
                layer.msg("修改成功！");
                //刷新父页面
                parent.location.reload();
            } else {
                layer.msg(data.msg);
            }
        })
        return false;
    });

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#choImg'
        ,url: '/pic/add'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#updateImg').attr('src', result); //图片链接（base64）
            });
        }
        ,auto:false
        ,bindAction:'#subImg'
        ,data: {
            id: function(){
                return pid;
            }
        }
        ,done: function(res){
            //如果上传失败
            if(res.code > 0){
                return layer.msg('上传失败');
            }
            //上传成功
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

})